package com.ruoyi.marketing.service;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.druid.support.json.JSONUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.redis.RedisCache;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.marketing.common.enums.ClientUrl;
import com.ruoyi.marketing.pojo.vo.AuthVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import springfox.documentation.spring.web.json.Json;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @description: ________
 * ___  __/______________
 * __  /_ ___  __ \  ___/
 * _  __/ __  /_/ / /__
 * /_/    _  .___/\___/
 * /_/
 * @author: www.fpcs.top
 * @create: 2021-05-24 09:52
 */
@Service
public class MarketingAuth2Service {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RedisCache redisCache;

    @Value("${marketing.appid}")
    private String app_id;

    public final String CACHE_Auth2_KEY = "Auth2:";
    @Value("${marketing.secret}")
    private String secret;


    /**
     * 获取token
     * @param sate
     * @param auth_code
     */
    public boolean auth(String sate, String auth_code) {
        Map<String, Object> map = new HashMap();
        map.put("app_id", app_id);
        map.put("secret", secret);
        map.put("grant_type", "auth_code");
        map.put("auth_code", auth_code);
        String post = HttpUtil.post(ClientUrl.GET_ACCESSTOKEN.getUrl(), map);
        JSONObject jsonObject = JSONUtil.parseObj(post);
        JSONObject data = JSONUtil.parseObj(jsonObject.get("data"));
        //新增了个字段不确定能否反序列化
        AuthVo authVo = JSONUtil.toBean(data, AuthVo.class);
        if (!StringUtils.isEmpty(data)) {
            JSONArray advertiserId = getAdvertiserId(authVo);
            authVo.setAdvertiserProId(advertiserId);
            //refresh 三十天有效期
            String s = JSONUtils.toJSONString(redisCache.getCacheObject(CACHE_Auth2_KEY + authVo.getAdvertiserId()));
            if (StringUtils.isEmpty(s) || s.equals("null")) {
                redisTemplate.opsForValue().set(CACHE_Auth2_KEY + authVo.getAdvertiserId(), JSONUtil.parseObj(authVo, false), 28, TimeUnit.DAYS);
                return true;
            }
            return true;
        }else {
            return false;
        }

    }


    /**
     * 刷新token
     * @param key
     * @param refresh_token
     * @return
     */
    public AjaxResult refreshToken(String key, String refresh_token) {
        if (redisCache.getCacheObject(key) != null) {
            String s = JSONUtils.toJSONString(redisCache.getCacheObject(key));
            AuthVo authVo1 = JSONUtil.toBean(s, AuthVo.class);
            Map<String, Object> map = new HashMap();
            map.put("app_id", app_id);
            map.put("secret", secret);
            map.put("grant_type", "refresh_token");
            map.put("refresh_token", refresh_token);
            String post = HttpUtil.post(ClientUrl.GET_REFRENSHTOKEN.getUrl(), map);
            JSONObject jsonObject = JSONUtil.parseObj(post);
            JSONObject data = JSONUtil.parseObj(jsonObject.get("data"));
            if (!StringUtils.isEmpty(data)) {
                AuthVo authVo = JSONUtil.toBean(data, AuthVo.class);
                JSONArray advertiserId = getAdvertiserId(authVo1);
                authVo1.setAccessToken(authVo.getAccessToken());
                authVo1.setRefreshToken(authVo.getRefreshToken());
                authVo1.setAdvertiserProId(advertiserId);
                redisTemplate.opsForValue().set(CACHE_Auth2_KEY + authVo1.getAdvertiserId(), JSONUtil.parseObj(authVo1, false), 28, TimeUnit.DAYS);
                return AjaxResult.success();
            }
        }
        return AjaxResult.error();
    }

    //测试
    public AjaxResult aaa(String getAdvertiserId) {
        Map map = new HashMap();
        map.put("advertiser_id", getAdvertiserId);
        String body = HttpRequest.get(ClientUrl.GET_ADVERTISER_ID.getUrl()).header("Access-Token", "4f1c3f0131916d162aba9e858063e9786540d59d")
                .form(map)
                .execute().body();
        JSONObject jsonObject = JSONUtil.parseObj(body);
        JSONArray objects = JSONUtil.parseArray(JSONUtil.parseObj(jsonObject.get("data")).get("list"));

        return AjaxResult.success();
    }

    private JSONArray getAdvertiserId(AuthVo authVo) {
        //获取管家id
        Map map1 = new HashMap();
        map1.put("advertiser_id", authVo.getAdvertiserId());
        String body = HttpRequest.get(ClientUrl.GET_ADVERTISER_ID.getUrl()).header("Access-Token", authVo.getAccessToken())
                .form(map1)
                .execute().body();
        JSONObject jsonObject1 = JSONUtil.parseObj(body);
        JSONArray objects = JSONUtil.parseArray(JSONUtil.parseObj(jsonObject1.get("data")).get("list"));
        return objects;
    }


}